<template>
	<view class=".form_box">
		<view class="t_form">
			<view class="item">
				<text>*企业名称</text>
				<input type="text" placeholder="请输入企业名称" v-model="form.title"/>
			</view>
			<view class="item">
				<text>*企业税号</text>
				<input type="text" placeholder="请输入企业税号" v-model="form.tax_number"/>
			</view>
			<view class="item">
				<text>*电子邮箱</text>
				<input type="text" placeholder="请输入电子邮箱" v-model="form.email"/>
			</view>
			<view class="item">
				<text>*手机号码</text>
				<input type="text" placeholder="请输入手机号码" v-model="form.mobile"/>
			</view>
			
			<view class="item_btn">
				<view class="item .item_bg">
					<button class="button wx_button btn-normal"  @click="getWxTitle">获取微信发票信息</button>
				</view>
				<view class="item .item_bg">
					<button class="button add_button btn-normal"  @click="handleSend">保存发票信息</button>
				</view>
			</view>
			
		</view>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { COMMON	} from "../../utils/commom.js"
	import { useAuthStore } from '@/stores/user.js';
	import { add_lnvoice, edit_lnvoice, save_lnvoice  } from "../../api/invoice.js"
	
	
	const form = ref({})
	const invoice_id = ref(null)
	
	// 编辑执行
	onLoad((option) =>{
		invoice_id.value = option.invoice_id
		if(option.invoice_id) get_lnvoice_detail(option.invoice_id)
	})
	
	
	// 获取微信发票信息
	function getWxTitle(){
		uni.chooseInvoiceTitle({
			success(res) {
				form.value = {
					title : res.title,
					tax_number : res.taxNumber
				}
			}
		})
	}
	
	// 保存信息
	function handleSend(){
		// 验证表单
		let emailReg = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/,
		    mobilePhone = /^1[3|4|5|6|7|8|9]\d{9}$/,
			email = emailReg.test(form.value.email),
			mobile = mobilePhone.test(form.value.mobile);
		if (!form.value.title) {
			COMMON.Toast(`企业名称不能为空`);
			return false
		}else if (!form.value.tax_number) {
			COMMON.Toast(`企业税号不能为空`);
			return false
		}else if (!email) {
			COMMON.Toast(`请输入正确的邮箱`);
			return false
		}else if(!mobile) {
			COMMON.Toast(`请输入正确的手机号`);
			return false
		}
		
		if(invoice_id.value){
			// 编辑保存
			save_lnvoice(form.value).then(res => {
				COMMON.re_back(res)
			})
		}else{
			// 添加保存
			add_lnvoice(form.value).then(res => {
				COMMON.re_back(res)
			})
		}
	}
	
	
	
	// 获取编辑详情
	function get_lnvoice_detail(invoice_id){
		edit_lnvoice(invoice_id).then(res => {
			let data = res.data;
			form.value = {
				title: data.title,
				tax_number: data.tax_number,
				email: data.email,
				mobile: data.mobile,
				invoice_id: data.invoice_id,
			}
		})
	}
	
	
	
</script>

<style lang="scss" scoped>
@import '@/static/css/form.scss';
</style>